package com.example.springboot.service.impl;

import com.example.springboot.dao.SysUserDao;
import com.example.springboot.dao.UserRoleDao;
import com.example.springboot.entity.SysUser;
import com.example.springboot.entity.UserRole;
import com.example.springboot.service.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (SysUser)表服务实现类
 *
 * @author makejava
 * @since 2021-09-06 11:55:47
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
	@Resource
	private SysUserDao sysUserDao;
	@Resource
	private UserRoleDao userRoleDao;


	/**
	 * 返回数据总数
	 *
	 * @return 纪录总数
	 */
	@Override
	public int queryUserCount() {
		return sysUserDao.queryUserCount();
	}

	/**
	 * 通过user查询单条数据
	 *
	 * @param user 用户信息
	 * @return 实例对象
	 */
	@Override
	public SysUser queryByUser(SysUser user) {
		return this.sysUserDao.queryByUser(user);
	}

	/**
	 * 通过ID查询单条数据
	 *
	 * @param id 主键
	 * @return 实例对象
	 */
	@Override
	public SysUser queryById(Long id) {
		return this.sysUserDao.queryById(id);
	}


	/**
	 * 查询多条数据
	 *
	 * @param offset 查询起始位置
	 * @param limit  查询条数
	 * @return 对象列表
	 */
	@Override
	public List<SysUser> queryAllByLimit(int offset, int limit) {
		return this.sysUserDao.queryAllByLimit(offset, limit);
	}

	@Override
	public SysUser insert(SysUser sysUser) {
		return null;
	}

	/**
	 * 新增数据
	 *
	 * @param sysUser 实例对象
	 * @return 实例对象
	 */
	@Override
	public SysUser insert(SysUser sysUser, List<Long> list) {
		if (this.sysUserDao.queryById(sysUser.getId()) == null) {
			return null;
		}

		sysUser.setStatus(0);
		sysUser.setCreatedate(new Date());
		int count = this.sysUserDao.insert(sysUser);

		if (count == 0) {
			sysUser = null;
		}
		return sysUser;
	}

	@Override
	public SysUser update(SysUser sysUser) {
		return null;
	}

	/**
	 * 修改数据
	 *
	 * @param sysUser 实例对象
	 * @return 实例对象
	 */
	@Override
	public SysUser update(SysUser sysUser, List<Long> list) {
		if (sysUserDao.queryByAccount(sysUser.getAccount()) == null) {
			return null;
		}

		this.userRoleDao.deleteById(sysUser.getId());
		for (int i = 0; i <= list.size(); i++) {
			Long roleid = list.get(i);
			UserRole userRole = new UserRole();
			userRole.setRoleid(roleid);
			userRole.setUserid(sysUser.getId());
			while (this.userRoleDao.insert(userRole) == 1) break;
		}

		sysUser.setStatus(0);
		sysUser.setModifydate(new Date());
		int count = this.sysUserDao.update(sysUser);

		if (count == 0) {
			sysUser = null;
		}
		this.sysUserDao.update(sysUser);
		return this.queryById(sysUser.getId());
	}

	@Override
	public boolean resetPassword(Long id) {
		SysUser sysUser = new SysUser();
		sysUser.setId(id);
		sysUser.setPassword("123456");
		return this.sysUserDao.update(sysUser) > 0;
	}

	/**
	 * 通过主键删除数据
	 *
	 * @param id 主键
	 * @return 是否成功
	 */
	@Override
	public boolean deleteById(Long id) {
		return this.sysUserDao.deleteById(id) > 0;
	}


}